package com.controller.common;

import org.springframework.stereotype.Component;

import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by Administrator on 2019/3/6.
 */
@ServerEndpoint("/log")
@Component
public class LogWebSocketHandle {

    private Process process;
    private InputStream inputStream;
    @OnOpen
    public void onOpen(Session session) {
        try {
            // 执行tail -f命令
            process = Runtime.getRuntime().exec("tail -f E:\\apache-tomcat-1\\logs\\catalina.2018-02-06.log");
            inputStream = process.getInputStream();
            // 一定要启动新的线程，防止InputStream阻塞处理WebSocket的线程
            TailLogThread thread = new TailLogThread(inputStream, session);
            thread.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public class TailLogThread extends Thread {
        private BufferedReader reader;
        private Session session;
        public TailLogThread(InputStream in, Session session) {
            this.reader = new BufferedReader(new InputStreamReader(in));
            this.session = session;
        }

        @Override
        public void run() {
            String line;
            try {
                while((line = reader.readLine()) != null) {
                    // 将实时日志通过WebSocket发送给客户端，给每一行添加一个HTML换行
                    session.getBasicRemote().sendText(line + "<br>");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
